package com.zh.note.huawei.twohundred.解压报文压缩报文还原;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * https://dream.blog.csdn.net/article/details/129259149
 */
public class Main {
    public static final Pattern PATTERN = Pattern.compile("[0-9]+\\[[a-z]+]");

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // String line = sc.nextLine();
        // String line = "3[m2[c]]";
        String line = "3[k]2[mn]";
        String res = solution(line);
        System.out.println(res);
    }

    private static String solution(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        Matcher matcher = PATTERN.matcher(line);
        // 递归出口
        if (!matcher.find()) {
            return line;
        }
        String group = matcher.group();
        // 找到[ 位置
        int pos = group.indexOf('[');
        // 获取中括号前面数字
        int count = Integer.parseInt(group.substring(0, pos));
        // 获取中括号里面字符
        String words = group.substring(pos + 1, group.length() - 1);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; i++) {
            sb.append(words);
        }
        // 把group替换成sb
        String replaced = line.replace(group, sb.toString());
        // 替换后继续查找
        return solution(replaced);

    }
}
